package com.gitee.ywj1352.nettyserver.serialize;

import com.gitee.ywj1352.nettyserver.FirstDemo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 *
 * @author: yangwenjie.a
 * @date: 2021/6/24 14:05
 * @description:
 */
public class ProtobufEncoder extends MessageToByteEncoder<FirstDemo.Demo> {


    @Override
    protected void encode(ChannelHandlerContext ctx, FirstDemo.Demo msg, ByteBuf out) throws Exception {

        // 将对象转换为byte
        byte[] bytes = msg.toByteArray();

        // 读取消息的长度
        int length = bytes.length;

        ByteBuf buf = Unpooled.buffer(2 + length);

        // 先将消息长度写入，也就是消息头
        buf.writeShort(length);

        // 消息体中包含我们要发送的数据
        buf.writeBytes(bytes);

        out.writeBytes(buf);

    }
}
